import Taro from "@tarojs/taro";
import React, { useEffect, useState, useRef } from "react";
import { View, Image, ScrollView, ITouchEvent } from "@tarojs/components";
import "./ChinaMap.scss";
import { IPoint } from "../../interface";

const mapList = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8]
];
interface IChinaMap {
  enableScroll: boolean;
  latitude: number;
  longitude: number;
}
interface IPosition {
  left: number;
  top: number;
}
function ChinaMap({ enableScroll, latitude, longitude }: IChinaMap) {
  const [scrollPosition, setScrollPosition] = useState<IPosition>();
  const scrollStartPosition = useRef<IPoint & IPosition>();
  const scrollMovePosition = useRef<IPoint[]>([]);
  const animateScrollIId = useRef<NodeJS.Timer | null>(null);
  const systemInfo = useRef<Taro.getSystemInfoSync.Result>();
  const mapSize = useRef<number>(0);

  useEffect(() => {
    systemInfo.current = Taro.getSystemInfoSync();

    const { windowWidth = 0, windowHeight = 0 } = systemInfo.current || {};

    mapSize.current = windowWidth * 8;

    const centerLocation: IPoint = {
      x: 105.5,
      y: 33.34
    };

    // const maxDis = 6000;

    const lng_step = 22.5;
    const lat_step = 18;

    function getScrollPosition() {
      let lng = (centerLocation.y - latitude) / (lat_step * 3);

      console.log({ lng });
      if (lng > 0) {
        // 南边
        lng -= Math.abs(Math.pow(lng, 2.5)) * 0.95;
      } else {
        lng -= lng * lng * lng * lng * 3.8;
      }

      const scrollLeft =
        mapSize.current *
          (0.5 + (longitude - centerLocation.x) / (lng_step * 3)) -
        windowWidth / 2;
      const scrollTop = mapSize.current * (0.5 + lng) - windowHeight / 2;

      return [scrollLeft, scrollTop];
    }

    const [left, top] = getScrollPosition();

    setScrollPosition({
      left,
      top
    });
  }, [latitude, longitude]);

  function handleMapTouch(event: ITouchEvent<any>) {
    // console.log("touch", event);
    if (scrollPosition) {
      event.stopPropagation();
      event.preventDefault();
      const { pageX: x, pageY: y } =
        event.touches[0] || event.changedTouches[0];

      switch (this) {
        case "Start":
          stopAnimateScroll();
          scrollStartPosition.current = {
            x,
            y,
            left: scrollPosition.left,
            top: scrollPosition.top
          };
          break;
        case "Move":
          console.log({ x, y });

          if (scrollMovePosition.current.length >= 2) {
            scrollMovePosition.current.shift();
          }
          if (scrollStartPosition.current) {
            const scrollLeftResult =
              scrollStartPosition.current.x -
              x +
              scrollStartPosition.current.left;
            const scrollTopResult =
              scrollStartPosition.current.y -
              y +
              scrollStartPosition.current.top;

            scrollMovePosition.current.push({
              x: scrollLeftResult,
              y: scrollTopResult
            });
            setScrollPosition({
              left: scrollLeftResult,

              top: scrollTopResult
            });
          }
          break;
        case "End":
          setTimeout(() => {
            if (scrollMovePosition.current.length >= 2) {
              const dy =
                scrollMovePosition.current[1].y -
                scrollMovePosition.current[0].y;

              const dx =
                scrollMovePosition.current[1].x -
                scrollMovePosition.current[0].x;

              if (Math.abs(dx) + Math.abs(dy) > 2 && systemInfo.current) {
                console.log("准备滚动", scrollMovePosition.current, dx, dy);
                // setScrollPosition({
                //   left: scrollMovePosition.current[1].x + 30 * dx,
                //   top: scrollMovePosition.current[1].y + 30 * dy
                // });
                let i = 0;
                let myLeft = 0;
                let myTop = 0;
                do {
                  i += 1;
                  myLeft = scrollMovePosition.current[1].x + i * dx;
                  myTop = scrollMovePosition.current[1].y + i * dy;
                } while (
                  myLeft >= 0 &&
                  myLeft + systemInfo.current.windowWidth <= mapSize.current &&
                  myTop >= 0 &&
                  myTop + systemInfo.current.windowHeight <= mapSize.current
                );
                console.log({ myLeft, myTop });

                animateScrollToPosition(myLeft, myTop, 2.5);
              }
            }
          }, 1);
          break;
        case "Cancel":
          break;
        default:
      }
    }
  }
  function stopAnimateScroll() {
    if (animateScrollIId.current !== null) {
      clearInterval(animateScrollIId.current);
    }
  }
  function animateScrollToPosition(dx: number, dy: number, time: number) {
    stopAnimateScroll();
    if (scrollPosition) {
      const count = (time * 1000) / 10;
      let i = 0;

      animateScrollIId.current = setInterval(() => {
        i += 1;
        setScrollPosition(position => {
          const { left = 0, top = 0 } = position || {};
          console.log(count, i, left, top);

          return {
            left: left + dx,
            top: top + dy
          };
        });
        dx *= 0.977;
        dy *= 0.977;

        if (i >= count) {
          if (animateScrollIId.current) {
            clearInterval(animateScrollIId.current);
            animateScrollIId.current = null;
          }
          // setScrollPosition({
          //   left: po.left,
          //   top: po.top
          // });
        }
      }, 10);
    }
  }
  return (
    <View className="ChinaMapPage">
      <ScrollView
        className="ChinaMapScrollView"
        scrollX={enableScroll}
        scrollY={enableScroll}
        scrollLeft={scrollPosition && scrollPosition.left}
        scrollTop={scrollPosition && scrollPosition.top}
        // scrollWithAnimation={scrollWithAnimation}
      >
        <View
          className="ChinaMap"
          style={{
            width: mapSize.current + "px",
            height: mapSize.current + "px"
          }}
        >
          {mapList.map(row => (
            <View className="row" key={row[0]}>
              {row.map(i => (
                <Image
                  className="map"
                  key={i}
                  src={`https://baikecount.com/OOZ/images/staticmap(${i})HD.png`}
                />
              ))}
            </View>
          ))}
        </View>
      </ScrollView>
      <View
        className="ChinaMapCover"
        onTouchStart={handleMapTouch.bind("Start")}
        onTouchMove={handleMapTouch.bind("Move")}
        onTouchEnd={handleMapTouch.bind("End")}
        onTouchCancel={handleMapTouch.bind("Cancel")}
      ></View>
    </View>
  );
}
export default ChinaMap;
